import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
import { NotificationService } from "../../shared/utils/notification.service";

declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-bom-sales',
	templateUrl: './bom-sales.component.html',
	styleUrls: ['./bom-sales.component.css']
})
export class BomSalesComponent implements OnInit {
	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			userNameFrom: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择对接人'
					}
				}
			}
		}
	}
	tableData: any[] = []; //table数据
	materialData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	userList: any; //用户数据
	bomSalesFrom: any = {
		id: null,
		receiveMan: '',
		receiveId: ''
	}
	userAllList: any; //用户数据
	projectList: any; //项目数据
	userId: string = ''; //用户名称
	userName: string = ''; //用户ID
	projectId: string = ''; //项目Id
	projectName: string = ''; //项目名称
	materialModalList = {
		id: ''
	};
	state: string = '';//发货状态
	dateType: string = '1'; // 时间类型
	salesType: string = '';//发货状态
	replenishmentType: string = '';//补货类型
	tableParamOrderType: string = '';//订单类型
	startTime = ''; //过滤条件-开始时间
	endTime = ''; //过滤条件-结束时间
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute, private notificationService: NotificationService) {
		activatedRoute.queryParams.subscribe(queryParams => {
		});
	}

	ngOnInit() {
		this.initBtn();
		this.initAllProjectName().then(() => {
			this.selectProjectName();
		});

		// 如果是跳转过来的会有
		let query = common.getCookie("expressDeliveryNumber")
		if (query) {
			this.searchKey = query;
			common.setCookie("expressDeliveryNumber", "")
		}
		this.initAllTableUser().then(() => {
			this.selectUserNameFrom();
			this.selectTableUserName();

			this.load();
		});

	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//刷新
	table_search() {
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load() {
		let tableSearch = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				receiveId: this.userId,
				receiveMan: this.userName,
				state: this.state,
				type: this.tableParamOrderType,
				salesType: this.salesType,
				replenishmentType: this.replenishmentType,
				projectId: this.projectId,
				projectName: this.projectName,
				searchKey: common.stringTrim(this.searchKey),
				dateType: this.dateType,
				startTime: this.startTime,
				endTime: this.endTime
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(tableSearch);
		this.jsonApiService.http("sellOrder/list.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		});
	}

	dataExceport() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				receiveId: this.userId,
				receiveMan: this.userName,
				state: this.state,
				type: this.tableParamOrderType,
				salesType: this.salesType,
				replenishmentType: this.replenishmentType,
				projectId: this.projectId,
				projectName: this.projectName,
				searchKey: common.stringTrim(this.searchKey),
				dateType: this.dateType,
				startTime: this.startTime,
				endTime: this.endTime,
				export: "1"
			}
		}
		let timeCheck = common.correctTime(data.parameters, ['export'])
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(data, 'gridPager', config.BaseURL + 'sellOrder/list.html')
	}

	/*
	 * 绑定对接人
	 */
	table_docking(row, _this, modal) {
		this.orderType = row.type;
		if (row.isReceive === 1) {
			this.jsonApiService.message("该条数据已绑定接收人并且是已接收状态，不能再次绑定")
			return
		}

		for (let item in this.bomSalesFrom) {
			this.bomSalesFrom[item] = row[item];
		}
		$("#userNameSelect2From").val(row.receiveId).trigger('change');

		// $("#bomSalesFrom").data('bootstrapValidator').resetForm();

		_this.stopPropagation();
		modal.show();
		// $("#bomSalesModal").modal("show")
	}
	/*
	 * 关闭弹窗
	 */
	modalClose(modal) {
		modal.hide();
		// $("#bomSalesModal").modal("hide")
		this.bomSalesFrom.id = '';
		this.delUserNameFrom();
		$("#bomSalesFrom").data('bootstrapValidator').resetForm();
	}

	//擦除用户所选值
	delUserNameFrom() {
		this.bomSalesFrom.receiveMan = '';
		this.bomSalesFrom.receiveId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2From').val("");
		$("#select2-userNameSelect2From-container").empty();
		$("#select2-userNameSelect2From-container").attr("title", "");
		$("#select2-userNameSelect2From-container").prepend(str);
		$("#userNameFrom").val("").change();
	}
	selectUserNameFrom() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#userNameSelect2From").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.userList,//为Select添加数据
					templateResult: this.formatRepo
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.bomSalesFrom.receiveMan = data.text;
					that.bomSalesFrom.receiveId = data.id;
					$("#userNameFrom").val(that.bomSalesFrom.receiveMan).change();
				});
			})
		})
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	/*
	 * form提交
	 */
	userControlSubmit(modal) {
		$('#bomSalesFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#bomSalesFrom').data('bootstrapValidator').isValid();  //验证是否通过

		if (isValid) {
			this.jsonApiService.http_obj("sellOrder/updateSellOrder.html", this.bomSalesFrom).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					this.modalClose(modal);
				}
			})
		}
	}
	//table刷新
	refresh() {
		this.load();
	}

	/*
	 * 关闭物料弹窗
	 */
	materialModalClose(modal) {
		modal.hide();
		// $("#bomMaterialModal").modal("hide")
	}

	/*
	 * 打开物料弹窗
	 */
	sellOrderId: any = "";
	isShowAddSell: any = false; //展示添加以及删除按钮
	orderType: any = '';// 订单类型
	materialModal(row, modal) {
		modal.show();
		this.sellOrderId = row.id;
		this.orderType = row.type;
		if (row.state == 1) {
			this.isShowAddSell = true
		} else {
			this.isShowAddSell = false
		}
		// $("#bomMaterialModal").modal("show")
		this.jsonApiService.http_obj("sellOrder/materialDetails.html", { "id": row.id }).subscribe(data => {
			this.materialData = data.data;
		});
	}
	// 导出物料明细 
	exportMaterialData(rowId) {
		var parameters = {
			id: rowId,
			type: this.orderType,
		};
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'sellOrder/exportMaterialDetails.html')
	}
	//擦除用户所选值
	delTableUserName() {
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameTableSelect').val("");
		$("#select2-userNameTableSelect-container").empty();
		$("#select2-userNameTableSelect-container").attr("title", "");
		$("#select2-userNameTableSelect-container").prepend(str);
		this.load();
	}
	//初始化select2 选项
	selectTableUserName() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#userNameTableSelect").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.userList,//为Select添加数据
					templateResult: this.formatRepo
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.userName = data.text;
					that.userId = data.id;
				});
			})
		})
	}
	//拉取
	initAllTableUser() {
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("sellOrder/getAllUserList.html", null).subscribe(data => {
				if (data.success) {
					var userList = data.data;
					var selectdata = [];
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].id,
							text: userList[i].name,
						}
						selectdata[i] = obj;
					}
				}
				that.userAllList = selectdata;
				that.userList = selectdata;
				resolve();
			})
		})
	}

	//擦除用户所选项目名称
	delProjectName() {
		this.projectName = '';
		this.projectId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#projectNameSelect').val("");
		$("#select2-projectNameSelect-container").empty();
		$("#select2-projectNameSelect-container").attr("title", "");
		$("#select2-projectNameSelect-container").prepend(str);
		this.load();
	}
	//初始化项目名称select2 选项
	selectProjectName() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#projectNameSelect").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.projectList//为Select添加数据
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.projectName = data.text;
					that.projectId = data.id;
				});
			})
		})
	}
	//拉取项目名称
	initAllProjectName() {
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("project/projectList.html", null).subscribe(data => {
				if (data.success) {
					var userList = data.data;
					var selectdata = [];
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].id,
							text: userList[i].projectName,
						}
						selectdata[i] = obj;
					}
				}
				that.projectList = selectdata;
				resolve();
			})
		})
	}
	isShowDelete = false; // 默认不显示删除按钮
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_BOM:sales')));
		if (!btnData) {
			return
		};
		for (let item of btnData) {
			if (item.sourceKey === "BOM:sales:deleteBtn" && item.parentId) {
				this.isShowDelete = true;
			}

		}
	}
	//发货单
	deleteBtn(row) {
		this.orderType = row.type;
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'sellOrderId=' + row.id + '&type=' + this.orderType;
			this.jsonApiService.http("sellOrder/deleteSellOrderBySellOrderId.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	expressCompany: any = ""; // 快递公司
	expressNumber: any = ""; // 快递单号
	expressList: any = []; // 物流信息情况
	// 订单物流的弹框展示
	showExpress(row, modal) {
		let reqdata = { sellOrderId: row.id }
		this.expressCompany = row.expressDeliveryUnit;
		this.expressNumber = row.expressDeliveryNumber;
		this.jsonApiService.http_obj("orderLogistics/getOrderLogisticsInfoBySellOrderId.html", reqdata).subscribe(res => {
			let list = res.data.data
			this.expressList = list ? list : [];
		})
		modal.show();

	}
	expressModalClose(modal) {
		modal.hide();
	}


	//添加物料
	// 物料实体 往后台传递的
	material: any = {
		addedCount: '',
		bomNumber: "",
		describe: "",
		materielNumber: "",
		materielType: 1,
		num: '',
		productName: "",
		setNum: '',
		totalCount: '',
		NumBer: 0,
		hullName: ''
	}
	materialList: any = [];
	materialDetailList: any = [];
	checkBomNumber: any = ''
	isCheck: any = "0"
	isDetailCheck: any = "0"
	// 选择物料类型
	clickMaterielType(value) {
		this.material.materielType = value
		this.clickBomNumber(this.checkBomNumber, this.isCheck, value);
	}
	// 添加Bom编码
	addBomMaterial(modal) {
		this.material = {
			addedCount: '',
			bomNumber: "",
			describe: "",
			materielNumber: "",
			materielType: 1,
			num: '',
			productName: "",
			setNum: '',
			totalCount: '',
			NumBer: 0,
			hullName: ''
		}
		this.materialList = [];
		//		modal.hide();
		let reqdata = {
			sellOrderId: this.sellOrderId,
			type: this.orderType,
		}
		this.jsonApiService.http_obj("sellOrder/querySellOrderMaterialByParam.html", reqdata).subscribe(data => {
			if (data.success) {
				if (this.orderType == 0) {  //销售订单物料明细
					//删除arr中的重复对象
					var arrId = [];
					for (var item of data.data) {
						if (arrId.indexOf(item['bomNumber']) == -1) {
							arrId.push(item['bomNumber']);
							this.materialList.push(item);
						}
					}
					this.checkBomNumber = this.materialList[0].bomNumber;
					this.isCheck = '0';
					this.clickBomNumber(this.checkBomNumber, this.isCheck, this.material.materielType);
				} else if (this.orderType == 1) {   //补货单物料明细   20210302  yangyang   新增补货单情况(物料明细)
					this.materialList = data.data;
					this.material = JSON.parse(JSON.stringify(this.materialList[0]));
					if (this.material.materielType == 1) {
						this.material.NumBer = 1;
					} else {
						this.material.NumBer = this.material.totalCount - this.material.addedCount;
					}
				}
			} else {
				this.jsonApiService.message(data.message);
			}
		})
		if (this.orderType == 0) {// 销售单明细添加弹窗  20210302  yangyang
			$('#addBomCodeModal').modal('show');
		} else if (this.orderType == 1) { // 补货单明细添加弹窗   20210302  yangyang
			$('#bomCodePageModal').modal('show');
		}
	}
	// 退货物料添加   20210302  yangyang
	materialClick(item) {
		this.material = item;
		if (this.material.materielType == 1) {
			this.material.NumBer = 1;
		} else {
			this.material.NumBer = this.material.totalCount - this.material.addedCount;
		}
	}
	clickBomNumber(id, index, materielType) {
		this.checkBomNumber = id;
		this.isCheck = index;
		this.materialDetailList = []
		let reqdata = {
			sellOrderId: this.sellOrderId,
			bomNumber: id || '',
			materielType: materielType,
			type: this.orderType,
		}
		this.jsonApiService.http_obj("sellOrder/querySellOrderMaterialByParam.html", reqdata).subscribe(data => {
			if (data.success) {
				//删除arr中的重复对象
				this.materialDetailList = data.data;
				this.material = JSON.parse(JSON.stringify(this.materialDetailList[0]));
				if (this.material.materielType == 1) {
					this.material.NumBer = 1;
				} else {
					this.material.NumBer = this.material.totalCount - this.material.addedCount;
				}
			} else {
				this.jsonApiService.message(data.message);
			}

		})
	}
	materialDetail(index) {
		this.isDetailCheck = index;
		this.material = JSON.parse(JSON.stringify(this.materialDetailList[index]))
		if (this.material.materielType == 1) {
			this.material.NumBer = 1;
		} else {
			this.material.NumBer = this.material.totalCount - this.material.addedCount;
		}
	}
	deleteBomBtn(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'sellOrderId=' + this.sellOrderId + '&materielId=' + row.materielId;
			this.jsonApiService.http("sellOrder/deleteMaterialForSellOrder.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.materialData = [];
				this.jsonApiService.http_obj("sellOrder/materialDetails.html", { "id": this.sellOrderId }).subscribe(data => {
					this.materialData = data.data;
				});
			})
		})
	}
	closeAddBomModal() {
		if (this.orderType == 0) {// 销售单明细添加弹窗关闭 20210302  yangyang
			$('#addBomCodeModal').modal('hide');
		} else if (this.orderType == 1) { // 补货单明细添加弹窗关闭   20210302  yangyang
			$('#bomCodePageModal').modal('hide');
		}
	}
	submitModal() {
		var that = this;
		if (parseInt(that.material.NumBer) > 0) { } else {
			this.jsonApiService.message('填写的数值必须大于0');
			return;
		}
		var materialObj
		if (that.material.materielType == 1) {
			if (that.material.hullName == '' || that.material.hullName == undefined || that.material.hullName == null) {
				this.jsonApiService.message('必须填写外壳编码');
				return;
			}
			materialObj = {
				bomNumber: that.material.bomNumber,
				describe: that.material.describe,
				materielNumber: that.material.materielNumber,
				materielType: that.material.materielType,
				num: 1,
				productName: that.material.productName,
				hullName: that.material.hullName,
			}
		} else {
			materialObj = {
				bomNumber: that.material.bomNumber,
				describe: that.material.describe,
				materielNumber: that.material.materielNumber,
				materielType: that.material.materielType,
				num: that.material.NumBer,
				productName: that.material.productName,
			}
		}
		var differNum = that.material.totalCount - that.material.addedCount;
		var materielJson = [];
		that.notificationService.smartMessageBox({
			title: "提示",
			content: "是否提交添加该物料？",
			buttons: '[确认][取消]'
		}, (ButtonPressed) => {
			if (ButtonPressed === "确认") {
				if (differNum < 0 || parseInt(materialObj.num) > differNum) {
					that.notificationService.smartMessageBox({
						title: "提示",
						content: "添加数量超过剩余所需总量(" + differNum + "),确定要添加吗？",
						buttons: '[确认][取消]'
					}, (ButtonPressed) => {
						if (ButtonPressed === "确认") {
							materielJson.push(materialObj)
							that.submitDetail(materielJson)
						}
						if (ButtonPressed === "取消") {
							that.notificationService.smallBox({
								content: "操作取消",
								timeout: 3000
							});
							return;
						}
					});
				} else {
					materielJson.push(materialObj);
					that.submitDetail(materielJson)
				}
			}
			if (ButtonPressed === "取消") {
				that.notificationService.smallBox({
					content: "操作取消",
					timeout: 3000
				});
				return;
			}
		});
	}
	submitDetail(data) {
		let reqdata = 'sellOrderId=' + this.sellOrderId + "&materielJsonStr=" + JSON.stringify(data) + '&type=' + this.orderType;
		this.jsonApiService.http("sellOrder/addSellOrderMaterial.html", reqdata).subscribe(data => {
			if (data.success) {
				this.closeAddBomModal();
				this.materialData = [];
				this.jsonApiService.http_obj("sellOrder/materialDetails.html", { "id": this.sellOrderId }).subscribe(data => {
					this.materialData = data.data;
				});
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	// 时间选中回调
	datePickerSelected(time) {
		this.startTime = time.startTime;
		this.endTime = time.endTime;
	}
}